
/* 

 	Declare Class CMD/Constructor - Meaning AjaxLab.Cmd = function is both
		a class declaration, as well as contructor method. 
		
	The default parameter eventhough is not shown passed in, but it's there 
		by default. It's called 'arguments' which is an array object. 
		
	Because it's a class, we can declar private variables, public properties. 
		for example, var copyright is my private variable
					 this.getCopyRight is my public property. 
	
	Because it's a construtor as well,  I can also call any method when get instantiated. 
		for example
*/
Type.registerNamespace("AjaxLab.Engine.Abstract");




AjaxLab.Engine.Abstract.Cmd= function(CommandPromptContainer, 
									  CommandPromptTextArea, 
									  DebugArea, 
									  CommandPromptRoot,
									  PathToLib)
{
				
			this.charactercount                     =   0;
	

			this.plugInCommandsQueue				=	new Object();
			this.enableAutoComplete					=	false;
			
			
			
			var cmdUtil;							
			var isDebug                             =   true;
  		 	var instance                            =   this;
			
            
			function Trim(myString)
            {   
                return  Trim_Trailing_LineFeed_Helper(myString);
            }
			
            function Trim_Trailing_LineFeed_Helper(s)
            {
                if(s!=null)
                {
                    while( (s.charCodeAt(s.length-1) == 10) || (s.charCodeAt(s.length-1) == 13) )
                    {
                        s = s.substring(0,s.length-1);
                    }
                }
                return s;
            }

            function Trim_Trailing_LineFeed(element){
                var s = element.value;  
                s = Trim_Trailing_LineFeed_Helper(s);
                element.value=s;
            }
    
            function scrollElementToEnd(element){
                if (typeof element.scrollTop != 'undefined' &&
                   typeof element.scrollHeight != 'undefined') {
                 element.scrollTop = element.scrollHeight;
               }
            }
	
	    	function rePosition()
			{
                var content = instance.getCmdUtil().getCommandPrompt();
                Trim_Trailing_LineFeed(content);
                scrollElementToEnd(content);
            }

	  		function setKeyDownEvent(e)
			{
				instance.getCmdUtil().Log4J.Debug("key down 1");
				instance.getCmdUtil().Log4J.Debug("page x:"+e.pageX + "y:"+e.pageY);
				
				
                var characterCode
                var text                    = instance.getCmdUtil().getCommandPrompt();
				

                if(e && e.which)
                { 
                    characterCode = e.which 
                }
                else if(document.getElementById)
                {
                     characterCode = e.keyCode
                }
                else{
                    characterCode = event.keyCode 
                }
                if(characterCode!=13 && characterCode!=8 && characterCode!=38)  //As long as it's not a backspace or carriage return.
                {   
                   instance.charactercount++; 
                }
                else if (characterCode ==8){
                     instance.charactercount--; 
                     if (instance.charactercount < 0)
                     {
                        text.value = text.value+">";
                        instance.charactercount = 0;
                     }
                }
                else if(characterCode==38){ //upper arrow key left:37 right:39 down:40
                    text.value=text.value;
                }
                else if(characterCode == 13) //If carriage return is pressed.
                {   
                    var commandstring = Trim(text.value);
                    var inputtext   = commandstring.substring(commandstring.length-instance.charactercount); 
                   	var trim_inputttext = inputtext.rTrim();
					instance.getCmdUtil().Log4J.Debug("CMD input text is :"+trim_inputttext);
					var command     = trim_inputttext.split(" ");
					instance.getCmdUtil().Log4J.Debug("CMD command:"+command[0]);
   					if(instance.plugInCommandsQueue==null)
					{
						instance.getCmdUtil().Log4J.Debug("CommandListnerStack is null");
					}
					else{
						instance.getCmdUtil().Log4J.Debug("CommandListnerStack is not null");
							
						if(inputtext=="")
						{
							instance.getCmdUtil().newPrompt();
						}
						else{
							var mytype = instance.plugInCommandsQueue[command[0].toUpperCase()];
							if(mytype!=null)
							{
								var basecommands = new mytype();
								basecommands.setCmdUtil(instance.getCmdUtil());
								var myDelegate = basecommands.returnCommandsDelegate();
								myDelegate(trim_inputttext);
							}
							else{
								instance.getCmdUtil().Log4J.Debug("No Command Found");
								instance.getCmdUtil().printToConsole(inputtext+" is not recognized as an internal or external command");
							}
						}
					}
                    instance.charactercount=0;
                }
            }
        
            function setKeyUpEvent(e)
			{
 			   instance.getCmdUtil().Log4J.Debug("key up");
               if(e && e.which)
                { 
                    e = e
                    characterCode = e.which 
                }
                else{
                    e = event
                    characterCode = e.keyCode 
                }
                if(characterCode == 13)
                {   
					rePosition();
                }
            }
			
			/* Public Properties */
			
			this.getCmdUtil			=	function()
			{
				return cmdUtil;
			}
			
			this.setCmdUtil			=	function(cmdutilParam)
			{
				cmdUtil = cmdutilParam;
			}
			
			
			this.setIsDebug = function (isdebugParam)
			{
				//instance.getCmdUtil().setIsDebug(isdebugParam);
				isDebug = isdebugParam;
			}
			
			this.getIsDebug =	function()
			{
				return isDebug;
			}

            this.addDefautlKeyListener                      =      function(){
                if (navigator.userAgent.indexOf("Safari") > 0) {
                    instance.getCmdUtil().getCommandPrompt().addEventListener("keydown", setKeyDownEvent,false);
                    instance.getCmdUtil().getCommandPrompt().addEventListener("keyup",setKeyUpEvent,false);
                } else if (navigator.product == "Gecko") {
                    instance.getCmdUtil().getCommandPrompt().addEventListener("keypress",setKeyDownEvent,false);
                    instance.getCmdUtil().getCommandPrompt().addEventListener("keyup",setKeyUpEvent,false);  
                } else {
					instance.getCmdUtil().Log4J.Debug("attachEvent");
                    instance.getCmdUtil().getCommandPrompt().attachEvent('onkeydown',setKeyDownEvent);
                    instance.getCmdUtil().getCommandPrompt().attachEvent('onkeyup',setKeyUpEvent);
                }
            }
			
			this.InitPlugIns								=	Function.abstractMethod;
			instance.registerDefaultLibraries(CommandPromptContainer, 
											  CommandPromptTextArea, 
											  DebugArea, 
											  CommandPromptRoot,
											  PathToLib);
}

AjaxLab.Engine.Abstract.Cmd.registerAbstractClass('AjaxLab.Engine.Abstract.Cmd');


AjaxLab.Engine.Abstract.Cmd.prototype = {
	
		registerDefaultLibraries		:	function(CommandPromptContainer, 
													 CommandPromptTextArea, 
													 DebugArea, 
													 CommandPromptRoot,
													 PathToLib
													 )
		{
				  var scriptLoader = new Sys.ScriptLoader();
				  var startHandler = Function.createDelegate(this, this.onPreLoad);
				  if(PathToLib==null)
				  {
					  PathToLib = "./";
				  }
				  var scripts = [
								   	PathToLib+'ScriptLibrary/AjaxLabCommandPrompt/Engine/Interface/ICommands.js',
									PathToLib+'ScriptLibrary/AjaxLabCommandPrompt/Engine/Abstract/Commands.js',
									PathToLib+'ScriptLibrary/AjaxLabCommandPrompt/Util/CmdUtil.js',
									PathToLib+'ScriptLibrary/AjaxLabCommandPrompt/Log/Log4J.js'
								 ];
				  var scriptcontext = [
									   CommandPromptContainer,
									   CommandPromptTextArea,
									   DebugArea,
									   CommandPromptRoot,
									   PathToLib
									  ]
				  scriptLoader.load(scripts, startHandler,scriptcontext);
		},
		
	 	onPreLoad							:	function(context)
		{
				var cmdUtil = new AjaxLab.Util.CmdUtil(context[0], context[1], context[2], context[3], context[4]);
				if(context[2]!=null)
				{
					cmdUtil.setIsDebug(true);
				}
				
				if(this.getIsDebug()==true)
				{
					cmdUtil.setIsDebug(true);;
				}
				else
				{
					cmdUtil.setIsDebug(false);
				}
				this.setCmdUtil(cmdUtil);
                this.addDefautlKeyListener();								
				this.InitPlugIns(context[4]);
		},
		
		registerCommandsPlugin:	function(ScriptPath,ClassName)
		{
		
			if(ScriptPath!=null)
			{
				var scriptLoader = new Sys.ScriptLoader();
				var startHandler = Function.createDelegate(this, this.onRegisterPlugin);
				var scripts = [ScriptPath];
				scriptLoader.load(scripts, startHandler, ClassName);
			}
		}, 
		
		onRegisterPlugin:	function(ClassName)
		{
			var tempclass = ClassName;
			var mytype = Type.parse(tempclass);
			var tempobject = new mytype();
			this.getCmdUtil().Log4J.Debug("got registered "+ClassName);
			var CommandNames = tempobject.getCommands();
			var commandarray = CommandNames.split("|");
			var x = 0;
            for (x=0; x<commandarray.length;x++)
            {
            	this.plugInCommandsQueue[commandarray[x].toUpperCase()]= mytype;
           	}	
		}
		
}